﻿using Leafing.Data;
using Leafing.Data.Common;
using Leafing.Data.Definition;
using System.Data;

namespace DBEntryHelper
{
    public static class DBHelper
    {
        public static T GetObject<T>(Condition sWhereClause) where T : class, IDbObject, new()
        {
            return DbEntry.GetObject<T>(sWhereClause);
        }

        public static T GetObjectBySql<T>(string sql) where T : class, IDbObject, new()
        {
            T obj;
            try
            {
                sql = sql.Replace("\r\n", " ");
                obj = DbEntry.ExecuteList<T>(sql)[0];
            }
            catch
            {
                obj = default(T);
            }
            return obj;
        }

        public static IList<T> GetObjects<T>(Condition sWhereClause, string sorderby) where T : class, IDbObject, new()
        {
            if (sorderby.Length > 0)
            {
                return DbEntry.From<T>().Where(sWhereClause).OrderBy(new OrderBy(sorderby)).Select();
            }
            else
            {
                return DbEntry.From<T>().Where(sWhereClause).Select();
            }
        }

        public static List<T> GetObjectsBySql<T>(string sql) where T : class, IDbObject, new()
        {
            sql = sql.Replace("\r\n", " ");
            return DbEntry.ExecuteList<T>(sql);
        }

        public static DataTable GetDataTableBySql(string sql)
        {
            return DbEntry.Provider.ExecuteDataset(sql).Tables[0];
        }
        /// <summary>
        /// Save method is not working now
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="OBJ"></param>
        public static void SaveObject<T>(T OBJ) where T : class, IDbObject, new()
        {
            DbEntry.Save(OBJ);
        }

        public static void InsertObject<T>(T OBJ) where T : class, IDbObject, new()
        {
            try
            {
                DbEntry.Insert(OBJ);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message.ToString());
            }
        }

        public static void UpdateObject<T>(T OBJ) where T : class, IDbObject, new()
        {
            DbEntry.Update(OBJ);
        }

        public static void DeleteObject<T>(T OBJ) where T : class, IDbObject, new()
        {
            DbEntry.Delete(OBJ);
        }

        public static int ExcuteSql(string sql)
        {
            return DbEntry.Provider.ExecuteNonQuery(sql);
        }

    }
}
